import { MockMethod } from 'vite-plugin-mock'
import { faker } from '@faker-js/faker'
import { ApiResponse } from '../../src/model/common-model'

// 定义配置类型
interface ProjectConfig {
  id: number;
  project_id: number;
  key: string;
  value: string;
  description: string;
  is_sensitive: boolean;
  created_at: string;
  updated_at: string;
}

// 生成随机配置键值对
const generateRandomConfigs = (projectId: number, count = 10) => {
  return Array.from({ length: count }).map((_, index) => {
    const id = index + 1
    const configTypes = ['db', 'server', 'cache', 'api', 'feature']
    const typeIndex = Math.floor(Math.random() * configTypes.length)
    const configType = configTypes[typeIndex]
    const key = `${configType}.${faker.word.sample()}.${faker.word.sample()}`
    
    return {
      id,
      project_id: projectId,
      key,
      value: faker.helpers.arrayElement([
        faker.internet.port().toString(),
        faker.internet.url(),
        faker.number.int({ min: 1, max: 1000 }).toString(),
        'true',
        'false',
        faker.lorem.word()
      ]),
      description: faker.lorem.sentence(),
      is_sensitive: Math.random() > 0.8,
      created_at: faker.date.past().toISOString(),
      updated_at: faker.date.recent().toISOString()
    } as ProjectConfig
  })
}

// 创建一个空的配置映射，只有当明确请求时才会为项目生成配置
const projectConfigsMap: Record<number, ProjectConfig[]> = {}

// 存储项目配置文件映射
const projectConfigFilesMap: Record<number, any[]> = {}

export default [
  // 获取项目配置文件列表 (新接口)
  {
    url: '/api/v1/config-files/:projectId/files',
    method: 'get',
    response: (req: any) => {
      const { projectId } = req.params
      
      // 返回空数组，表示新项目没有配置文件
      const configFiles = projectConfigFilesMap[Number(projectId)] || []
      
      return {
        code: 0,
        errorMsg: '',
        data: configFiles
      }
    }
  },
  
  // 创建项目配置文件 (新接口)
  {
    url: '/api/v1/config-files/:projectId/files',
    method: 'post',
    response: (req: any) => {
      const { projectId } = req.params
      const { body } = req
      
      if (!projectConfigFilesMap[Number(projectId)]) {
        projectConfigFilesMap[Number(projectId)] = []
      }
      
      const newFileId = (projectConfigFilesMap[Number(projectId)].length + 1)
      const newFile = {
        id: newFileId,
        project_id: Number(projectId),
        file_path: body.file_path,
        description: body.description || '',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      }
      
      projectConfigFilesMap[Number(projectId)].push(newFile)
      
      return {
        code: 0,
        errorMsg: '',
        data: newFile
      }
    }
  },
  
  // 删除项目配置文件 (新接口)
  {
    url: '/api/v1/config-files/:projectId/files/:fileId',
    method: 'delete',
    response: (req: any) => {
      const { projectId, fileId } = req.params
      
      if (!projectConfigFilesMap[Number(projectId)]) {
        return {
          code: 404,
          errorMsg: `项目ID ${projectId} 没有任何配置文件`,
          data: null
        }
      }
      
      const files = projectConfigFilesMap[Number(projectId)]
      const fileIndex = files.findIndex(f => f.id === Number(fileId))
      
      if (fileIndex >= 0) {
        files.splice(fileIndex, 1)
        
        return {
          code: 0,
          errorMsg: '',
          data: {
            success: true
          }
        }
      } else {
        return {
          code: 404,
          errorMsg: `文件ID ${fileId} 不存在`,
          data: null
        }
      }
    }
  },
  
  // 获取项目配置列表
  {
    url: '/api/v1/configs/:projectId',
    method: 'get',
    response: (req: any) => {
      const { projectId } = req.params
      const { page = 1, page_size = 10 } = req.query
      
      // 确保新创建的项目没有默认配置
      const configs = projectConfigsMap[Number(projectId)] || []
      const total = configs.length
      const start = (Number(page) - 1) * Number(page_size)
      const end = start + Number(page_size)
      const configsList = configs.slice(start, end)
      
      return {
        code: 0,
        errorMsg: '',
        data: configsList,
        total
      }
    }
  },
  
  // 获取项目配置详情
  {
    url: '/api/v1/configs/:projectId/:configKey',
    method: 'get',
    response: (req: any) => {
      const { projectId, configKey } = req.params
      
      const configs = projectConfigsMap[Number(projectId)] || []
      const config = configs.find(c => c.key === configKey)
      
      if (config) {
        return {
          code: 0,
          errorMsg: '',
          data: config
        }
      } else {
        return {
          code: 404,
          errorMsg: `配置键 ${configKey} 不存在`,
          data: null
        }
      }
    }
  },
  
  // 创建项目配置
  {
    url: '/api/v1/configs/:projectId',
    method: 'post',
    response: (req: any) => {
      const { projectId } = req.params
      const { body } = req
      
      const configs = projectConfigsMap[Number(projectId)] || []
      const existingConfigIndex = configs.findIndex(c => c.key === body.key)
      
      // 检查键是否已存在
      if (existingConfigIndex >= 0) {
        // 更新已存在的配置
        const updatedConfig = {
          ...configs[existingConfigIndex],
          value: body.value,
          description: body.description,
          is_sensitive: body.is_sensitive !== undefined ? body.is_sensitive : configs[existingConfigIndex].is_sensitive,
          updated_at: new Date().toISOString()
        }
        
        configs[existingConfigIndex] = updatedConfig
        
        return {
          code: 0,
          errorMsg: '',
          data: updatedConfig
        }
      } else {
        // 创建新配置
        const newConfig = {
          id: configs.length + 1,
          project_id: Number(projectId),
          key: body.key,
          value: body.value,
          description: body.description || '',
          is_sensitive: body.is_sensitive || false,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        }
        
        configs.push(newConfig)
        projectConfigsMap[Number(projectId)] = configs
        
        return {
          code: 0,
          errorMsg: '',
          data: newConfig
        }
      }
    }
  },
  
  // 更新项目配置
  {
    url: '/api/v1/configs/:projectId/:configKey',
    method: 'put',
    response: (req: any) => {
      const { projectId, configKey } = req.params
      const { body } = req
      
      const configs = projectConfigsMap[Number(projectId)] || []
      const configIndex = configs.findIndex(c => c.key === configKey)
      
      if (configIndex >= 0) {
        const updatedConfig = {
          ...configs[configIndex],
          value: body.value !== undefined ? body.value : configs[configIndex].value,
          description: body.description !== undefined ? body.description : configs[configIndex].description,
          updated_at: new Date().toISOString()
        }
        
        configs[configIndex] = updatedConfig
        
        return {
          code: 0,
          errorMsg: '',
          data: updatedConfig
        }
      } else {
        return {
          code: 404,
          errorMsg: `配置键 ${configKey} 不存在`,
          data: null
        }
      }
    }
  },
  
  // 删除项目配置
  {
    url: '/api/v1/configs/:projectId/:configKey',
    method: 'delete',
    response: (req: any) => {
      const { projectId, configKey } = req.params
      
      // 如果项目配置Map不存在，则无需删除
      if (!projectConfigsMap[Number(projectId)]) {
        return {
          code: 404,
          errorMsg: `项目ID ${projectId} 没有任何配置`,
          data: null
        }
      }
      
      const configs = projectConfigsMap[Number(projectId)]
      const configIndex = configs.findIndex(c => c.key === configKey)
      
      if (configIndex >= 0) {
        const removed = configs.splice(configIndex, 1)[0]
        
        return {
          code: 0,
          errorMsg: '',
          data: {
            success: true
          }
        }
      } else {
        return {
          code: 404,
          errorMsg: `配置键 ${configKey} 不存在`,
          data: null
        }
      }
    }
  },
  
  // 批量创建项目配置
  {
    url: '/api/v1/configs/:projectId/batch',
    method: 'post',
    response: (req: any) => {
      const { projectId } = req.params
      const { body } = req
      const { configs: newConfigs } = body
      
      if (!Array.isArray(newConfigs) || newConfigs.length === 0) {
        return {
          code: 400,
          errorMsg: '请求格式不正确',
          data: null
        }
      }
      
      // 确保项目配置Map存在
      if (!projectConfigsMap[Number(projectId)]) {
        projectConfigsMap[Number(projectId)] = []
      }
      
      const configs: ProjectConfig[] = projectConfigsMap[Number(projectId)] || []
      const createdConfigs: ProjectConfig[] = []
      
      for (const newConfig of newConfigs) {
        const existingConfigIndex = configs.findIndex(c => c.key === newConfig.key)
        
        if (existingConfigIndex >= 0) {
          // 更新已存在的配置
          configs[existingConfigIndex] = {
            ...configs[existingConfigIndex],
            value: newConfig.value,
            description: newConfig.description || configs[existingConfigIndex].description,
            is_sensitive: newConfig.is_sensitive !== undefined ? newConfig.is_sensitive : configs[existingConfigIndex].is_sensitive,
            updated_at: new Date().toISOString()
          }
          
          createdConfigs.push(configs[existingConfigIndex])
        } else {
          // 创建新配置
          const createdConfig = {
            id: configs.length + 1,
            project_id: Number(projectId),
            key: newConfig.key,
            value: newConfig.value,
            description: newConfig.description || '',
            is_sensitive: newConfig.is_sensitive || false,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString()
          }
          
          configs.push(createdConfig as ProjectConfig)
          createdConfigs.push(createdConfig as ProjectConfig)
        }
      }
      
      projectConfigsMap[Number(projectId)] = configs
      
      return {
        code: 0,
        errorMsg: '',
        data: createdConfigs
      }
    }
  },
  
  // 批量删除项目配置
  {
    url: '/api/v1/configs/:projectId/batch',
    method: 'delete',
    response: (req: any) => {
      const { projectId } = req.params
      const { body } = req
      const { keys } = body
      
      if (!Array.isArray(keys) || keys.length === 0) {
        return {
          code: 400,
          errorMsg: '请求格式不正确',
          data: null
        }
      }
      
      const configs = projectConfigsMap[Number(projectId)] || []
      
      for (const key of keys) {
        const configIndex = configs.findIndex(c => c.key === key)
        if (configIndex >= 0) {
          configs.splice(configIndex, 1)
        }
      }
      
      projectConfigsMap[Number(projectId)] = configs
      
      return {
        code: 0,
        errorMsg: '',
        data: {
          success: true
        }
      }
    }
  },
  
  // 导入配置
  {
    url: '/api/v1/configs/:projectId/import',
    method: 'post',
    response: (req: any) => {
      const { projectId } = req.params
      
      // 模拟从文件导入的配置
      const importedConfigs = Array.from({ length: 5 }).map((_, index) => {
        return {
          id: 1000 + index,
          project_id: Number(projectId),
          key: `imported.config.key${index + 1}`,
          value: faker.lorem.word(),
          description: `从文件导入的配置 ${index + 1}`,
          is_sensitive: false,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        }
      })
      
      const configs = projectConfigsMap[Number(projectId)] || []
      projectConfigsMap[Number(projectId)] = [...configs, ...importedConfigs]
      
      return {
        code: 0,
        errorMsg: '',
        data: importedConfigs
      }
    }
  }
] as MockMethod[]
